package com.sitanyun.merchant.guide.weiht;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * 6.0以上运行时权限管理
 * Created by wuxy on 2017/4/29.
 */

public class PermissionsUtils {

    Activity activity;

    public PermissionsUtils(Activity activity) {
        this.activity = activity;
    }

    /**
     * 判断多个权限是否全部注册
     *
     * @param permissions
     * @return true 全部注册
     */
    public boolean checkPermissions(String... permissions) {
        for (String permission : permissions) {
            if (!checkPermission(permission)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断单个权限是否缺少
     *
     * @param permission
     * @return true 已经注册
     */
    private boolean checkPermission(String permission) {
//        ContextCompat.checkSelfPermission，主要用于检测某个权限是否已经被授予，
// 方法返回值为PackageManager.PERMISSION_DENIED或者PackageManager.PERMISSION_GRANTED。当返回DENIED就需要进行申请授权了。
        return ContextCompat.checkSelfPermission(activity, permission) ==
                PackageManager.PERMISSION_GRANTED;
    }
//
    /**
     * 申请权限
     *
     * @param permission 权限数组
     * @param requestCode 请求码，用于处理返回的结果
     */
    public void requestPermissions(String permission, int requestCode) {
        // Should we show an explanation?
//        这个API主要用于给用户一个申请权限的解释，该方法只有在用户在上一次已经拒绝过你的这个权限申请。
// 也就是说，用户已经拒绝一次了，你又弹个授权框，你需要给用户一个解释，为什么要授权，则使用该方法。//Manifest.permission.READ_CONTACTS
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
        }
    }


    /**
     * 检测权限是否全部申请成功 用于处理返回结果
     *
     * @param grantResults
     * @return
     */
    public boolean checkGrantResults(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(activity, "未获取权限", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }



    //危险权限列表
    /**
     联系人
    group:android.permission-group.CONTACTS
    permission:android.permission.WRITE_CONTACTS
    permission:android.permission.GET_ACCOUNTS
    permission:android.permission.READ_CONTACTS
    拨号
    group:android.permission-group.PHONE
    permission:android.permission.READ_CALL_LOG
    permission:android.permission.READ_PHONE_STATE
    permission:android.permission.CALL_PHONE
    permission:android.permission.WRITE_CALL_LOG
    permission:android.permission.USE_SIP
    permission:android.permission.PROCESS_OUTGOING_CALLS
    permission:com.android.voicemail.permission.ADD_VOICEMAIL
    日历
    group:android.permission-group.CALENDAR
    permission:android.permission.READ_CALENDAR
    permission:android.permission.WRITE_CALENDAR
    相机
    group:android.permission-group.CAMERA
    permission:android.permission.CAMERA
    传感器
    group:android.permission-group.SENSORS
    permission:android.permission.BODY_SENSORS
    定位
    group:android.permission-group.LOCATION
    permission:android.permission.ACCESS_FINE_LOCATION
    permission:android.permission.ACCESS_COARSE_LOCATION
    存储
    group:android.permission-group.STORAGE
    permission:android.permission.READ_EXTERNAL_STORAGE
    permission:android.permission.WRITE_EXTERNAL_STORAGE
    麦克风
    group:android.permission-group.MICROPHONE
    permission:android.permission.RECORD_AUDIO
    短信
    group:android.permission-group.SMS
    permission:android.permission.READ_SMS
    permission:android.permission.RECEIVE_WAP_PUSH
    permission:android.permission.RECEIVE_MMS
    permission:android.permission.RECEIVE_SMS
    permission:android.permission.SEND_SMS
    permission:android.permission.READ_CELL_BROADCASTS
     **/


    public static final String PACKAGE = "package:";


//    /**
//     * 判断权限集合
//     *
//     * @param permissions 检测权限的集合
//     * @return 权限已全部获取返回true，未全部获取返回false
//     */
//    public boolean checkPermissions(String... permissions) {
//        for (String permission : permissions) {
//            if (!checkPermission(permission)) {
//                return false;
//            }
//        }
//        return true;
//    }
//
//    /**
//     * 判断权限是否获取
//     *
//     * @param permission 权限名称
//     * @return 已授权返回true，未授权返回false
//     */
//    public boolean checkPermission(String permission) {
//        return ContextCompat.checkSelfPermission(mContext, permission) == PackageManager.PERMISSION_GRANTED;
//    }


    /**请求权限
     * @param permissions
     * @param resultCode
     */
    public void requestPermissions(String[] permissions, int resultCode){
        ActivityCompat.requestPermissions((Activity) activity,
                permissions,
                resultCode);
    }
    /**
     * 获取权限
     *
     * @param resultCode
     * @return
     */
    public void permissionsCheck(String permission, int resultCode) {
        // 注意这里要使用shouldShowRequestPermissionRationale而不要使用requestPermission方法
        // 因为requestPermissions方法会显示不在询问按钮
        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) activity, permission)) {
            //如果用户以前拒绝过改权限申请，则给用户提示
            showMissingPermissionDialog();
        } else {
            //进行权限请求
            ActivityCompat.requestPermissions((Activity) activity,
                    new String[]{permission},
                    resultCode);
        }
//        ActivityCompat.requestPermissions((Activity) mContext, new String[]{permission},resultCode);
    }


    // 显示缺失权限提示
    private void showMissingPermissionDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        final AlertDialog alertDialog = builder.create();

        builder.setMessage("当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。\n\n最后点击两次后退按钮，即可返回。");
        // 拒绝, 退出应用
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });

        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.show();
    }

    // 启动应用的设置
    public void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse( PACKAGE + activity.getPackageName()));
        activity.startActivity(intent);
    }

}
